<?php

namespace App\Http\Repositories\Relation;

use App\Http\Repositories\Repository;
use App\Models\UserRoleRelation;

/**
 * 用户角色关联
 */
class UserRoleRepo extends Repository
{
    const MODEL =  UserRoleRelation::class;

    public function create($user_id, $role_id)
    {
        $item = $this->query()->where([
            ['user_id', '=', $user_id],
            ['role_id', '=', $role_id],
        ])->first();
        if (!empty($item)) abort(422, '该用户已经存在该角色');

        return $this->createOne(['user_id' => $user_id, 'role_id' => $role_id]);
    }

    public function delete($user_id, $role_id)
    {
        return $this->query()->where('user_id', $user_id)->where('role_id', $role_id)->delete();
    }

    /**
     * 根据roleid获取userid
     */
    public function getUserIdsByRoleIds(string $role_ids)
    {
        $role_ids = explode(',', $role_ids);
        $result=$this->query()->select('user_id')->whereIn('role_id', $role_ids)->get();

        $result=!empty($result) ? $result->toArray() : [];

        return array_column($result,'user_id');
    }
}
